
const fastify = require('fastify')({ logger: true });
const dotenv = require('dotenv') // 加载 .env 文件中的环境变量
const {logger} = require('./utils/logger')
// 解析命令行参数
const args = process.argv.slice(2);
const env = args.find(arg => /^ENV=/.test(arg)) || 'ENV=' + process.env.ENV || 'ENV=dev';
let envFile = env.split('=')[1];
if (!['local', 'test', 'prod'].includes(envFile)) {
    envFile = "test"
}
dotenv.config({ path: `./.env.${envFile}` });
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
// 引入 fastify-cors 插件
fastify.register(require('fastify-cors'), {
    origin: '*',
    methods: ['GET', 'POST'],
    allowedHeaders: ['Content-Type', 'apptoken', 'token'],
});
fastify.register(require('./routes'));
fastify.register(require('@fastify/cookie'));

// 请求拦截插件
fastify.addHook('onRequest', (request, reply, done) => {
    // 记录请求日志
    logger.reqLog(request,new Date().toISOString());
    done();
});

// 响应拦截插件
fastify.addHook('onSend', (request, reply, payload, done) => {
    // 记录响应日志
    const response = reply.serialize(payload);
    console.log(response,'response------')
    logger.resLog(response,new Date().toISOString());
    done();
});

// fastify.register(require('fastify-swagger'), {
//     routePrefix: '/',
//     swagger: {
//         info: {
//             title: 'Test swagger',
//             description: 'Testing the Fastify swagger API',
//             version: '0.1.0'
//         }
//     }
// });

if (cluster.isMaster && numCPUs>4) {
    for (let i = 0; i < 3; i++) {
        cluster.fork({
            workerId: i,
            port: 32080
        });
    }

    cluster.on('exit', (worker, code, signal) => {
        console.log(`Worker ${worker.process.pid} died`);
        cluster.fork({
            workerId: worker.env.workerId,
            port: worker.env.port
        });
    });
} else {
    const workerId = process.env.workerId;
    const port = process.env.port;

    fastify.listen(32080, '0.0.0.0',(err) => {
        if (err) {
            console.error(err);
            process.exit(1);
        }
        console.log(`后端服务启动成功`);
    });
}